<template>
	<view>
		<view class="goods-list">
			<view v-for="(goods, i) in goodsList" :key="i" @click="goToDetail(goods)">
				<my-goods :goods="goods"></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				//查询商品列表的入参
				queryObj: {
					query: '', //查询关键词
					cid: '', //分类ID
					pagenum: 1, //页数索引
					pagesize: 10, //每页长度
				},
				goodsList: [], //商品列表数据
				total: 0, //商品总数
				isLoading: false, //上拉触底节流阀
			};
		},
		onLoad(options) {
			this.queryObj.query = options.query || '';
			this.queryObj.cid = options.cid || '';
			this.getGoodsList();
		},
		methods: {
			//获取商品列表数据
			async getGoodsList(cb){
				this.isLoading = true;
				
				const {data: res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj);
				
				this.isLoading = false;
				cb && cb();
				
				if(res.meta.status !== 200){
					//请求失败
					return uni.$showMsg();
				}
				
				this.goodsList = [...this.goodsList, ...res.message.goods];
				this.total = res.message.total;
			},
			//跳转至商品详情
			goToDetail(goods){
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
				});
			},
		},
		onReachBottom() {
			if(this.queryObj.pagenum * this.queryObj.pagesize >= this.total){
				//数据加载完毕
				return uni.$showMsg('数据加载完毕！');
			}
			
			if(this.isLoading){
				//正在请求下一页数据
				return;
			}
			
			this.queryObj.pagenum++;
			this.getGoodsList();
		},
		onPullDownRefresh() {
			this.queryObj.pagenum = 1;
			this.total = 0;
			this.goodsList = [];
			this.isLoading = false;
			this.getGoodsList(() => uni.stopPullDownRefresh());
		},
	}
</script>

<style lang="scss">
.goods-list {
	
}
</style>
